package column

import (
	"encoding/json"
	"fmt"
	"game/game-db/orm/metag"
	"reflect"
	"strings"
	"unsafe"
)

type StructColumnMeta struct {
	StringColumnMeta
	formatter string
}

func (t *StructColumnMeta) FillValue(objField reflect.Value, fieldValue reflect.Value) {
	jsonValue := reflect.New(objField.Type())
	jsonObj := jsonValue.Interface()
	err := json.Unmarshal([]byte(fieldValue.Interface().(string)), jsonObj)
	if err != nil {
		fmt.Printf("字段%v在解释值%v时发生错误%v\n", t.fieldName, fieldValue.Interface().(string), err)
	} else {
		setValue(objField, reflect.ValueOf(jsonObj).Elem())
	}
}
func (t *StructColumnMeta) TakeValue(objField reflect.Value) interface{} {
	var obj interface{}
	if objField.CanInterface() {
		obj = objField.Interface()
	} else {
		objField = reflect.NewAt(objField.Type(), unsafe.Pointer(objField.UnsafeAddr())).Elem()
		obj = objField.Interface()
	}
	if t.formatter == "json" {
		byteValue, err := json.Marshal(obj)
		if err == nil {
			result := string(byteValue)
			if result == "null" {
				return nil
			} else {
				return result
			}
		} else {
			return nil
		}
	} else {
		panic("未支持的格式化方式")
	}
}

func NewStructField(structField reflect.StructField, columnMetag metag.ColumnMetag) IColumnMeta {
	var meta StructColumnMeta
	meta.fillBaseValue(structField, columnMetag)
	if columnMetag.Length <= 0 {
		meta.length = 255
	} else {
		meta.length = columnMetag.Length
	}
	if columnMetag.Extra != "" {
		meta.extra = strings.Split(columnMetag.Extra, ",")
	} else {
		meta.extra = []string{}
	}
	meta.formatter = columnMetag.Formatter
	if meta.formatter == "" {
		meta.formatter = "json"
	}
	return &meta
}
